package org.linlinjava.litemall.admin.service;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.admin.shiro.AuthUtils;
import org.linlinjava.litemall.admin.shiro.LitemallAdminExt;
import org.linlinjava.litemall.core.util.AmountUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallCashesMapper;
import org.linlinjava.litemall.db.dao.LitemallMoneyLogsMapper;
import org.linlinjava.litemall.db.dao.LitemallStoreMapper;
import org.linlinjava.litemall.db.dao.StoreMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.*;

/**
 * @Description:	提现管理
 * @Author:			Coach tam
 * @Company:		坚持灵活  灵活坚持
 * @CreateDate:		2021-4-14 10:04:50
 */
@Slf4j
@Service
@Transactional
public class AdminCashesService {
    @Autowired
    private LitemallCashesMapper cashesMapper;
    @Autowired
    private LitemallStoreMapper storeMapper;
    @Autowired
    private StoreMapper myStoreMapper;
    @Autowired
    private LitemallMoneyLogsMapper moneyLogsMapper;
    @Autowired
    private LogHelper logHelper;
    public LitemallCashes findById(Integer id) {
        return cashesMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public void add(LitemallCashes entity) {

        entity.setAddTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());

        //判断商家状态
        Integer storeId = AuthUtils.getStoreId();
        LitemallAdminExt admin = AuthUtils.getAdmin();
        LitemallStore litemallStore = storeMapper.selectByPrimaryKey(storeId);
        if (litemallStore.getFrozen() > 0) {
            throw new RuntimeException("同时只能有一个提现申请");
        }
        if(litemallStore.getDeleted()){
            throw new RuntimeException("商家状态不可用");
        }
        //元转分
        Long money = Long.valueOf(AmountUtils.changeY2F(entity.getMoney()));
//        Long money = entity.getMoney();
        //判断商家余额
        if (litemallStore.getBalance()==0||litemallStore.getBalance() < money) {
            throw new RuntimeException("商家余额不足");
        }
        try {
            //扣除商户对应余额
            myStoreMapper.updateBalance(storeId, money);
            entity.setMoney(money);
            entity.setStoreId(storeId);
            entity.setUserId(admin.getId());
            cashesMapper.insertSelective(entity);
            logHelper.logTixianSucceed("添加提现申请", "申请ID:"+entity.getId().toString());
        } catch (Exception e) {
            log.error("商家{}提现失败",storeId,e);
            throw new RuntimeException("提现失败");
        }

    }

    public int updateById(LitemallCashes entity) {
        entity.setUpdateTime(LocalDateTime.now());
        return cashesMapper.updateByPrimaryKeySelective(entity);
    }

    public List<LitemallCashes> querySelective(String name,Integer page, Integer size, String sort, String order) {
        LitemallCashesExample example = new LitemallCashesExample();
        LitemallCashesExample.Criteria criteria = example.createCriteria();

        Integer storeId = AuthUtils.getStoreId();
        if (storeId != null) {
            criteria.andStoreIdEqualTo(storeId);
        }

        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }


        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return cashesMapper.selectByExample(example);
    }

    public int count() {
        LitemallCashesExample example = new LitemallCashesExample();
        return (int) cashesMapper.countByExample(example);
    }

    public List<LitemallCashes> findCashes(String name) {
        LitemallCashesExample example = new LitemallCashesExample();
        example.or().andNameEqualTo(name);
        return cashesMapper.selectByExample(example);
    }

    @Transactional
    public void approval(LitemallCashes entity) {
        //TODO 是否发短信提醒
        Integer storeId = entity.getStoreId();
        //判断是否通过
        if (entity.getCashStatus() == 1) {
            //删除冻结余额
            myStoreMapper.updateFrozen(0L,storeId);
            //新增审批日志
            logHelper.logTixianSucceed("提现审批通过", "申请ID:"+entity.getId().toString());
        } else if(entity.getCashStatus() == 2) {
            //恢复解冻余额
            myStoreMapper.freeFrozen(storeId);
            //新增审批日志
            logHelper.logTixianFail("提现审批拒绝", "申请ID:"+entity.getId().toString()+",拒绝原因:"+entity.getRefuseInfo());
        }
        entity.setUpdateTime(LocalDateTime.now());
        cashesMapper.updateByPrimaryKey(entity);
    }
}
